package com.sabeot.library.web.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sabeot.library.hibernate.dto.User;
import com.sabeot.library.hibernate.dto.UserDetails;
import com.sabeot.library.service.UserService;
import com.sabeot.library.web.bean.UserBean;


@Controller
@RequestScoped
@ManagedBean(name="editUserController")
public class EditUserController {

	Logger logger = Logger.getLogger(EditUserController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserBean userBean;
	
	public void saveUser(){
		try{
			
			User u = new User(userBean.getLogin(), userBean.getPassword());
			UserDetails uDetails = new UserDetails(userBean.getFirstName(), userBean.getLastName(), userBean.getEmail(), 
					userBean.getAlternateEMail(), userBean.getBirthDate());
			
			uDetails.setUser(u);
			u.setUserDetails(uDetails);
			
			userService.saveUser(u);
			
			logger.info("New user created: "+userBean.getLogin());
			
			userBean = new UserBean();
			
		}catch(ConstraintViolationException e){
			logger.error("User with login: "+ userBean.getLogin() +" already exist! \n" + e.getSQLException().getLocalizedMessage());
		}catch(Exception e){
			
			logger.error("User"+ userBean.getLogin() +" creation failed!", e);
			
		}
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public UserService getUserService() {
		return userService;
	}
	
}
